<template>
  <div class="addGroupFriend autoGrow flex-row">
    <div class="addOperate flex-column">
      <div class="subTitle">添加群好友</div>
      <div>
        <input
        type="text"
        placeholder="请输入搜索关键词"
        v-model="keyword"
        class="searchInput layui-input"/>
      </div>
      <div class="toggleOwner">
        <label>
          <input type="radio"
          name="manager"
          value="manager"
          @change="changeGroupType"
          :checked="groupType=='manager'"> 群主
        </label>
        <label>
          <input type="radio"
          name="manager"
          value="member"
          @change="changeGroupType"
          :checked="groupType=='member'"> 非群主
        </label>
        
      </div>
      <div class="groupListTitle">群聊（{{groups.length}}）</div>
      <div class="groupList autoGrow">
        <label v-for="(group) in filterGroups" :key="group.id">
           <user-list-item
            :showBadge="false"
            :showLastMessage="false"
            currentUserWxid=""
            :item="group">
            <template v-slot:checkbox>
              <input type="checkbox"
                :checked="checkedGroups.includes(group.wxid)"
                class="select"
                @change="toggleSelect(group)">
            </template>
            <template v-slot:bottomInfo>
              <div>
                <span>群成员{{group.personnum}} </span>
                <span>非好友{{group.personnum - group.friendNum}}</span>
              </div>
            </template>
          </user-list-item>
        </label>
       
      </div>
    </div>
    <transition name="slide-fade">
      <div class="groupMemberListContainer  autoGrow flex-column" v-if="!showRecords">
        <div class="listContainerHead flex-row">
          <div class="subTitle">群成员列表<span class="fontGrey">(已隐藏是好友关系的用户)</span></div>
          <input type="text"
            placeholder="请输入关键词"
            v-model="memberSearchKeyword"
            class="searchInput layui-input">
        </div>
        <div class="memberListContainer autoGrow flex-column">
          <div class="checkboxes">
            <label>
              <input type="radio" name="gender" :checked="filter==''" value="" @change="changeFilter"> 全部（{{totalMemberCount}}）
            </label>
            <label>
              <input type="radio" name="gender" :checked="filter=='male'" value="male" @change="changeFilter"> 男（{{maleMemberCount}}）
            </label>
            <label>
            <input type="radio" name="gender" :checked="filter=='female'" value="female" @change="changeFilter"> 女（{{femaleMemberCount}}）  
            </label>
            
          </div>
          <div class="memberList autoGrow flex-row">
            <label v-for="(member) in groupMembers" :key="member.id">
              <user-list-item
              :item="member"
              :showBadge="false"
              :showLastMessage="false"
              :showGender="true"
            >
              <template v-slot:checkbox>
                <input type="checkbox"
                  :checked="checkedMembers.filter(c=>c.wxid==member.wxid).length!=0"
                  class="select"
                  @change="toggleSelectMember(member, $event)">
              </template>
              <template v-slot:bottomInfo>
                <div>
                  {{member.groupnick}}
                </div>
              </template>
            </user-list-item>
            </label>
            
          </div>
          <div class="memberCountDesc">
            已选择{{checkedGroups.length}}个群的{{checkedMembers.length}}个成员
          </div>
        </div>
        <div class="sendRequests flex-row">
          <button
            @click="sendNow"
            class="layui-btn layui-btn-sm">
            即时发送
          </button>
          <button
            @click="setSendTime"
            class="layui-btn layui-btn-primary layui-btn-sm">
            定时发送
          </button>
        </div>
        <div class="toggleRecordsList" @click="toggleRecordsList(true)">
          添加记录<i class="layui-icon-up layui-icon"></i>
        </div>
      </div>
    </transition>
    <transition name="slide-fade">
      <add-friend-record
        v-if="showRecords"
        @cancel="cancelSend"
        :initialRecords="records">
        <div class="toggleRecordsList" @click="toggleRecordsList(false)">
          收起<i class="layui-icon-down layui-icon"></i>
        </div>
      </add-friend-record>
    </transition>
    <time-picker
      v-if="showDatePicker"
      @closeTimePicker="()=>this.showDatePicker=false"
      @submit="submitSendTime">
    </time-picker>
    <custom-dialog
      v-if="showDialog"
      :closeDialog="closeDialog"
      title="添加好友">
      <div class="wainInfo">
        <p>添加好友数量{{checkedMembers.length}}</p>
        <p>今日添加好友验证上限：200</p>
      </div>
      <template v-slot:buttons>
        <div class="buttons">
            <button class="layui-btn layui-btn-normal" @click="closeDialog">再次编辑</button>
            <button class="layui-btn layui-btn-normal" @click="forceSend">按上限发送</button>
        </div>
      </template>
    </custom-dialog>
  </div>
</template>
<script>
import UserListItem from '@/components/userListItem';
import CustomDialog from '@/components/customDialog';
import TimePicker from '@/components/timePicker';
import AddFriendRecord from '@/components/addFriendRecord';
import {pathOr} from 'ramda'
import { mapState } from 'vuex';
import pinyin from '@/lib/pinyin'

export default {
  name: 'AddGroupFriend',
  data() {
    return {
      showDatePicker: false,
      showDialog: false,
      keyword: '',
      memberSearchKeyword: '',
      groupType: 'manager',
      showRecords: false,
      filter: '',
      groups: [],
      checkedGroups: [],
      checkedGroupMembers: [],
      checkedMembers: [],
      records: [],
      memberMap:{},

      totalMemberCount:0,
      maleMemberCount:0, 
      femaleMemberCount:0
    }
  },
  components: {
    UserListItem,
    AddFriendRecord,
    TimePicker,
    CustomDialog
  },
  mounted() {
    this.$form.render()
    const service = pathOr({},['services',0],this.params)
    if (service.csid ) {
      this.initGroups(service)
    }
    this.initRecord(service)
  },
  props: ['params'],
  methods: {
    changeGroupType(e) {
      this.groupType = e.target.value;
    },
    changeFilter(e) {
      this.filter = e.target.value
    },
    toggleSelect(group) {
      if (this.checkedGroups.includes(group.wxid)) {
        this.checkedGroups = this.checkedGroups.filter(item=>{
          return item!=group.wxid
        })
      } else {
        this.checkedGroups.push(group.wxid)
      }
    },
    initRecord(service) {
      const csId = this.uistate.adminid
      this.$api.friend.inviteFriendHistory({
        csId,
        // wxAccount:service.wxid,
        type: 2
      }).then(data=>{
        try {
          this.records = this.transRecords(data)
        } catch (error) {
          console.log(error) 
        }
      }).catch(e=>this.$msg(e))
    },
     transRecords(data){
      return data.map(item=>{
        const service = this.services.filter(s=>s.wxid==item.wxaccountid)[0]
        if(service){
          return {
            ...item,
            name: service.name,
            avatar: service.avatar,
            time: this.formatTime(item.starttime),
            type: 'instant',
            status: 'ongoing',
            completeCount: item.senditemcount,
            showDetail: false,
            detailType: 'adopt',
            targets: []
          }
        }else{
          return {}
        }
        
      })
    },
    initGroups(service) {
      this.$api.group.list({
        csid: service.csid,
        wxaccount: service.wxid
      }).then(data=>{
        this.groups = this.transGroupData(data)
      })
    },
    toggleSelectMember(member, e) {
      if (e.target.checked) {
        this.checkedMembers.push(member)
      } else {
        this.checkedMembers = this.checkedMembers.filter(m=>m.wxid!=member.wxid)
      }
    },
    cancelSend(record) {
      this.$api.friend.cancel(record).then(rs=>{
          this.records = this.records.filter(item=>item.id!==record.id)
          this.$msg('操作成功')
        })
    },
    forceSend() {
      this.send(Date.now())
    },
    sendNow() {
      if (this.checkedMembers.length > 200) {
        return this.showDialog = true
      }
      this.send()
    },
    
    async send(time){
      const {services, sleepFrom, sleepTo, minSecond, maxSecond, maxCount, verifyInfo, settingId} = this.params
      if (!services || !services[0]) {
        return this.$msg('没有选择客服账号')
      }
      if(maxSecond<minSecond){
        return this.$msg('间隔时间设置错误')
      }
      if( !this.checkedMembers[0] ){
        return this.$msg('没有选择好友账号')
      }
      const service = services[0]
      let params = {
        csid: service.csid,
        wxaccountid: service.wxid,
        validationmsg: verifyInfo,
        sleepstart: sleepFrom,
        sleepend: sleepTo,
        intervalstart: minSecond,
        intervalend: maxSecond,
        daylimit: maxCount
      }
      try {
        if (settingId) {
          await this.$api.friend.updateInviteSetting({
            ...params,
            id: settingId
          })
        } else {
          await this.$api.friend.insertInviteSetting(params)
        }
        const groupFriend = this.checkedMembers.map(item=>{
          console.log(item)
          return { 
            "groupNo": item.groupno, 
            "groupAvatar": "",
            "groupName":"",
            "friendWxId":item.alias||item.wxid,
            "friendNick":item.nick,
            "friendAvatar":item.avatar,
            "friendWxAccount": item.alias||item.wxid
            }
        })
        try {
          await this.$api.friend.inviteFriend({
            csid: service.csid,
            wxaccountid: service.wxid,
            starttime: time,
            type: 2,
            itemcount: this.checkedMembers.length,
            groupFriend
          }) 
          this.$msg('任务创建成功')
        } catch (error) {
          this.$msg('任务创建失败')
        }
        
      } catch(e) {
        this.$msg(e)
      }
    },
    toggleRecordsList(bool) {
      const service = pathOr({},['services',0],this.params)
      if(service.wxid&&bool){
        this.initRecord(service)
      }
      
      this.showRecords = bool
    },
    closeDialog() {
      this.showDialog = false
    },
    setSendTime() {
      this.showDatePicker = true
    },
    submitSendTime(time) {
      this.send(time)
      this.showDatePicker = false;
    },
  },
  computed: {
    ...mapState(['services','uistate']),
    filterGroups(){
      const isShowManager = this.groupType === 'manager'
      const keyword = pinyin.getFullChars(this.keyword).toLocaleLowerCase() 

      return this.groups.filter(item=>{
        const chars = pinyin.getFullChars(item.groupname).toLocaleLowerCase() ;
        if(isShowManager){
          return item.isfirst === 1 && chars.indexOf(keyword)>-1
        }else{
          return item.isfirst !== 1 && chars.indexOf(keyword)>-1
        }
         
      })
      
    },
    groupMembers() {
      let checkedGroupMembers = []
      let result = []
      const memberSearchKeyword = pinyin.getFullChars(this.memberSearchKeyword).toLocaleLowerCase()
      const filter = this.filter
      let totalMemberCount = 0,
          maleMemberCount = 0, 
          femaleMemberCount = 0

      this.checkedGroups.forEach(id=>{
        const members = this.memberMap[id]
        if(members){
          checkedGroupMembers = checkedGroupMembers.concat(members)     
        }
      })

      checkedGroupMembers.forEach(member=>{
        if(member.ismycontact === 1)return
        if( member.gender == 1 ){
          maleMemberCount += 1
        }else if( member.gender == 2 ){
          femaleMemberCount += 1
        }
        const chars = pinyin.getFullChars(member.nick+''+member.wxid).toLocaleLowerCase()
        if( chars.indexOf(memberSearchKeyword)<0 )return
        if(filter === ''){
          result.push(member)
        }else if(filter === 'male'){
          if( member.gender == 1 ){
            result.push(member) 
          }
        }else{
          if( member.gender == 2 ){
            result.push(member) 
          }
        }
      })
      
      this.totalMemberCount = checkedGroupMembers.length
      this.maleMemberCount = maleMemberCount
      this.femaleMemberCount = femaleMemberCount

      return result;
      
    },
     
  },
  watch: {
    'params.services': function(val, oldVal) {
      val = val||[]
      oldVal = oldVal||[]
      const newAccount = val[0]||{}
      const oldAccount = oldVal[0]||{}
      if(newAccount.id !== oldAccount.id && newAccount.id){
        const service = val[0]
        // this.initRecord(service)
        this.initGroups(service)

        this.checkedGroupMembers = [] 
        this.checkedMembers = []
        this.checkedGroups = []
        //this.records = []

        this.keyword = ''
        this.memberSearchKeyword = ''
      }
       
    },
    checkedGroups(val) {
      const groups = this.groups.filter(group => val.includes(group.id)&&!this.memberMap[group.id] )
      
      groups.forEach(group=>{
        let users = this.$api.group.members({
          csId: group.csid,
          wxAccount: group.wxaccount,
          groupNo: group.groupno
        })
        .then(users=>{
          users = users || []
          users = this.transUserData(users)  
          this.$set(this.memberMap,group.id,users)
        })
        .catch(e=>{})
      })

       
    }
  }
}
</script>
